<?php

namespace App\Http\Logic\Admin;

use App;
use App\Common\Status;
use \App\Models\Job;
use \App\Models\RecruitPositionCategory;
use \App\Models\Business;
use App\Helper\Helper;
use Illuminate\Support\Facades\DB;

class NotesLogic
{
    use App\Http\Logic\NoteOtherLogic;

    /**
     * @param $params
     * @param $pageSize
     * @param $page
     * @return \Illuminate\Support\Collection
     */
    public static function getNoteList($params, $pageSize, $page,$source = "list")
    {
        $where[] = ['is_deleted', '=', Status::NOT_DELETE];

        # 工作状态
        if (isset($params['work_st']) && $params['work_st']) {
            $where[] = ['work_st', '=', $params['work_st']];
        }

        if (isset($params['sex']) && $params['sex']) {
            $where[] = ['sex', '=', $params['sex']];
        }

        if (isset($params['mobile']) && $params['mobile']) {
            $where[] = ['mobile', '=', $params['mobile']];
        }


        if (isset($params['search_name']) && $params['search_name']) {
            $where[] = ['user_name', 'like', '%'.trim($params['search_name']).'%'];
        }

        if (isset($params['birth']) && $params['birth']) {
            $sy = strtotime("-".$params['birth']." years");
            $ey = strtotime("-".($params['birth'] + 1)." years");
            $where[] = ['birth', '>=', $sy];
            $where[] = ['birth', '>', $ey];
        }


        if (isset($params['work_date'])) {
            $where[] = ['work_year', '=', $params['work_date']];
        }

        # 工作年限
//        if (isset($params['work_year']) && $params['work_year']) {
//            if ($params['work_year'] == 2) {
//                $where[] = ['work_year', '>=', 1];
//            } elseif ($params['work_year'] == 3) {
//                $where[] = ['work_year', '>=', 1];
//                $where[] = ['work_year', '<=', 3];
//            } elseif ($params['work_year'] == 4) {
//                $where[] = ['work_year', '>=', 3];
//                $where[] = ['work_year', '<=', 5];
//            } elseif ($params['work_year'] == 5) {
//                $where[] = ['work_year', '>=', 5];
//                $where[] = ['work_year', '<=', 10];
//            } elseif ($params['work_year'] == 6) {
//                $where[] = ['work_year', '<=', 10];
//            }
//        }

        $specialityMobiles = $salaryDataMobiles = $intentionCateMobiles = $intentionCityMobiles = $educationMobiles = [];

        # 城市 【后期需要改造  当数据太多】
        if (isset($params['city']) && $params['city']) {
            $intentionCity = DB::table("recruit_notes_intention")->where(
                [
                    ["status", '=', Status::REGULAR],
                    ["is_deleted", '=', Status::NOT_DELETE],
                    ["work_city", '=', $params['city']],
                ]
            )->select("mobile")->get();
            if (!$intentionCity->isEmpty()) {
                $intentionCityMobiles = ($intentionCity->map(function ($value) {
                    return (array)$value;
                })->toArray());
            }
        }


        # 分类 【后期需要改造  当数据太多】
        if (isset($params['position_category_id']) && $params['position_category_id']) {
            $intentionCate = DB::table("recruit_notes_intention")->where(
                [
                    ["status", '=', Status::REGULAR],
                    ["is_deleted", '=', Status::NOT_DELETE],
                    ["position_category_id", '=', $params['position_category_id']],
                ]
            )->select("mobile")->get();

            if (!$intentionCate->isEmpty()) {
                $intentionCateMobiles = ($intentionCate->map(function ($value) {
                    return (array)$value;
                })->toArray());
            }


        }

        # 学历 【后期需要改造  当数据太多】
        if (isset($params['education']) && $params['education']) {
            $education = DB::table("recruit_educational_back")->where(
                [
                    ["status", '=', Status::REGULAR],
                    ["is_deleted", '=', Status::NOT_DELETE],
                    ["education", '=', $params['education']],
                ]
            )->select("mobile")->get();

            if (!$education->isEmpty()) {
                $educationMobiles = ($education->map(function ($value) {
                    return (array)$value;
                })->toArray());
            }
        }


        # 专业 【后期需要改造  当数据太多】
        if (isset($params['speciality']) && $params['speciality']) {
            $speciality = DB::table("recruit_educational_back")->where(
                [
                    ["status", '=', Status::REGULAR],
                    ["is_deleted", '=', Status::NOT_DELETE],
                    ["speciality", 'like', '%' . $params['speciality'] . '%'],
                ]
            )->select("mobile")->get();

            if (!$speciality->isEmpty()) {
                $specialityMobiles = ($speciality->map(function ($value) {
                    return (array)$value;
                })->toArray());
            }
        }

        if (isset($params['salary']) && $params['salary']) {
            $salary = [["status", '=', Status::REGULAR], ["is_deleted", '=', Status::NOT_DELETE]];
            if ($params['salary'] == 1) {
                $salary[] = ["salary1", '<=', 3000];
            } elseif ($params['salary'] == 2) {
                $salary[] = ["salary1", '>=', 3000];
                $salary[] = ["salary2", '<=', 5000];
            } elseif ($params['salary'] == 3) {
                $salary[] = ["salary1", '>=', 5000];
                $salary[] = ["salary2", '<=', 8000];
            } elseif ($params['salary'] == 4) {
                $salary[] = ["salary1", '>=', 8000];
                $salary[] = ["salary2", '<=', 10000];
            } elseif ($params['salary'] == 5) {
                $salary[] = ["salary1", '>=', 10000];
                $salary[] = ["salary2", '<=', 15000];
            } elseif ($params['salary'] == 6) {
                $salary[] = ["salary1", '>=', 15000];
                $salary[] = ["salary2", '<=', 20000];
            } elseif ($params['salary'] == 7) {
                $salary[] = ["salary1", '>=', 20000];
                $salary[] = ["salary2", '<=', 30000];
            } elseif ($params['salary'] == 8) {
                $salary[] = ["salary1", '>=', 30000];
                $salary[] = ["salary2", '<=', 50000];
            } elseif ($params['salary'] == 9) {
                $salary[] = ["salary1", '>=', 50000];
                $salary[] = ["salary2", '<=', 100000];
            } elseif ($params['salary'] == 10) {
                $salary[] = ["salary2", '>=', 100000];
            }
            $salaryData = DB::table("recruit_notes_intention")->where($salary)->select("mobile")->get();

            if (!$salaryData->isEmpty()) {
                $salaryDataMobiles = ($salaryData->map(function ($value) {
                    return (array)$value;
                })->toArray());
            }
        }

        if (isset($params['st_dt']) && $params['st_dt']) {
            $where[] = ['created_at', '>=', strtotime($params['st_dt'].' 00:00:00')];
        }
        if (isset($params['en_dt']) && $params['en_dt']) {
            $where[] = ['created_at', '<=', strtotime($params['en_dt'].' 23:59:59')];
        }

        $array  = array_unique(array_merge($salaryDataMobiles, $specialityMobiles, $intentionCateMobiles,
            $intentionCityMobiles, $educationMobiles),
            SORT_REGULAR);
        $result = array_column($array, "mobile");


        $query  = DB::table('recruit_notes')
            ->where($where)
            ->when($result, function ($query, $result) {
                return $query->whereIn('mobile', $result);
            })->orderBy("created_at", "desc");

        if($source == "list") {
            $data  = $query->offset($pageSize * ($page - 1))
                ->limit($pageSize)
                ->get();
            $count = self::getCount($where, $result);
            if ($data->isNotEmpty()) {
                $res = self::getIntentionInfo($data);
                return ['list' => $res, 'total' => $count, 'page' => $page, 'pageSize' => $pageSize];
            }
            return ['list' => [], 'total' => $count, 'page' => $page, 'pageSize' => $pageSize];
        } else {
            $data  = $query->get();
            if ($data->isNotEmpty()) {
                return self::getIntentionInfo($data);
            }
            return [];
        }

    }


    private static function getCount($where, $result)
    {
        return DB::table('recruit_notes')
            ->where($where)
            ->when($result, function ($query, $result) {
                return $query->whereIn('mobile', $result);
            })->count();
    }

    # 获取求职意向 recruit
    private static function getIntentionInfo($data)
    {
        foreach ($data as $datum) {
            # 学历
            $educational = DB::table('recruit_educational_back')
                ->select([
                    DB::raw('GROUP_CONCAT(education SEPARATOR ",") education'),
                    DB::raw('GROUP_CONCAT(university_name SEPARATOR ",") university_name'),
                    DB::raw('GROUP_CONCAT(speciality SEPARATOR ",") speciality')
                ])
                ->where(
                    [
                        ["mobile", "=", $datum->mobile],
                        ["status", "=", Status::REGULAR],
                        ["is_deleted", "=", Status::NOT_DELETE]
                    ])
                ->groupByRaw('mobile')
                ->get();

            $datum->educational_info = '';
            if (!$educational->isEmpty()) {
                $educationalTmp = explode(',', $educational[0]->education);
                foreach ($educationalTmp as $km => $item) {
                    $datum->educational_info .= ',' . Status::EDUCATION[$item];
                }
            }

            $datum->educational_info       = ltrim($datum->educational_info, ',');
            $datum->work_city_name         = "";
            $datum->position_category_name = "";
            # 意向城市
            $intention = DB::table('recruit_notes_intention')
                ->select(["work_city", "position_category_id"])
                ->where([
                    ["mobile", '=', $datum->mobile],
                    ["status", "=", Status::REGULAR],
                    ["is_deleted", "=", Status::NOT_DELETE]
                ])->get();

            if ($intention->isNotEmpty()) {
                $ctIds               = $intention->pluck('work_city');
                $positionCategoryIds = $intention->pluck('position_category_id');
                $cts                 = DB::table('recruit_city')->whereIn("id", $ctIds)->select([DB::raw('GROUP_CONCAT(name SEPARATOR ",") work_city_name')])->first();
                $positionCategory    = DB::table('recruit_position_category')->whereIn("id", $positionCategoryIds)->select([DB::raw('GROUP_CONCAT(name SEPARATOR ",") position_category_name')])->first();

                if ($cts) {
                    $datum->work_city_name = $cts->work_city_name;
                }
                if ($positionCategory) {
                    $datum->position_category_name = $positionCategory->position_category_name;
                }
            }

            $tmp = self::GetAnnex($datum->mobile);
            if ($tmp && count($tmp) > 0) {
                $datum->att_name = $tmp["name"];
                $datum->annex_path = $tmp["path"];
                $datum->annex_id = $tmp["id"];
            }
        }
        return $data;
    }


    private static function getDataInfo($data)
    {
        foreach ($data as $datum) {
            $area_name        = DB::table('recruit_city')->select("name")->where("id", $datum->area)->first();
            $city_name        = DB::table('recruit_city')->select(["parentid", "name"])->where("id", $datum->city)
                ->first();
            $datum->area_name = $area_name ? $area_name->name : '';
            $datum->city_name = $city_name ? $city_name->name : '';

            $datum->work_exp_info  = Status::WORK_EXP[$datum->work_exp];
            $datum->job_type_info  = Status::JOB_TYPE[$datum->job_type];
            $datum->education_info = Status::EDUCATION[$datum->education];
            $datum->hot_info       = $datum->hot == 1 ? '否' : '是';

        }
        return $data;
    }
}
